package com.ruoyi.web.controller.pack;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.pack.domain.PackProject;
import com.ruoyi.pack.domain.PackProjectMaterial;
import com.ruoyi.pack.service.IPackProjectService;
import com.ruoyi.pack.service.IPackProjectMaterialService;

/**
 * 项目Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/pack/project")
public class PackProjectController extends BaseController
{
    @Autowired
    private IPackProjectService packProjectService;
    
    @Autowired
    private IPackProjectMaterialService packProjectMaterialService;

    /**
     * 查询项目列表
     */
    @PreAuthorize("@ss.hasPermi('pack:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(PackProject packProject)
    {
        startPage();
        List<PackProject> list = packProjectService.selectPackProjectList(packProject);
        return getDataTable(list);
    }

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('pack:project:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PackProject packProject)
    {
        List<PackProject> list = packProjectService.selectPackProjectListForExport(packProject);
        ExcelUtil<PackProject> util = new ExcelUtil<PackProject>(PackProject.class);
        util.exportExcel(response, list, "项目数据");
    }

    /**
     * 获取项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('pack:project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId)
    {
        return success(packProjectService.selectPackProjectDetailsByProjectId(projectId));
    }

    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('pack:project:add')")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PackProject packProject)
    {
        if ("1".equals(packProjectService.checkProjectCodeUnique(packProject)))
        {
            return error("新增项目'" + packProject.getProjectName() + "'失败，项目编码已存在");
        }
        packProject.setCreateBy(getUsername());
        
        // 检查是否包含物料或仓库权限配置，使用增强版新增方法
        if ((packProject.getMaterialList() != null && !packProject.getMaterialList().isEmpty()) ||
            (packProject.getWarehouseOperationList() != null && !packProject.getWarehouseOperationList().isEmpty()))
        {
            return success(packProjectService.insertPackProjectWithDetails(packProject));
        }
        else
        {
        return toAjax(packProjectService.insertPackProject(packProject));
        }
    }

    /**
     * 修改项目
     */
    @PreAuthorize("@ss.hasPermi('pack:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping("/{projectId}")
    public AjaxResult edit(@PathVariable("projectId") Long projectId, @Validated @RequestBody PackProject packProject)
    {
        // 确保使用路径参数中的projectId
        packProject.setProjectId(projectId);
        
        if ("1".equals(packProjectService.checkProjectCodeUnique(packProject)))
        {
            return error("修改项目'" + packProject.getProjectName() + "'失败，项目编码已存在");
        }
        packProject.setUpdateBy(getUsername());
        
        // 检查是否包含物料或仓库权限操作，使用增强版修改方法
        if ((packProject.getMaterialOperations() != null && !packProject.getMaterialOperations().isEmpty()) ||
            (packProject.getWarehouseOperations() != null && !packProject.getWarehouseOperations().isEmpty()))
        {
            return success(packProjectService.updatePackProjectWithOperations(packProject));
        }
        else
        {
        return toAjax(packProjectService.updatePackProject(packProject));
        }
    }

    /**
     * 删除项目
     */
    @PreAuthorize("@ss.hasPermi('pack:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Long[] projectIds)
    {
        return toAjax(packProjectService.deletePackProjectByProjectIds(projectIds));
    }

    /**
     * 删除单个项目（增强版，支持force和cleanupData参数）
     */
    @PreAuthorize("@ss.hasPermi('pack:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectId}/enhanced")
    public AjaxResult removeEnhanced(@PathVariable Long projectId, 
                                   Boolean force, 
                                   Boolean cleanupData)
    {
        if (force == null) force = false;
        if (cleanupData == null) cleanupData = false;
        
        return success(packProjectService.deletePackProjectByProjectIdEnhanced(projectId, force, cleanupData));
    }

    /**
     * 校验项目编码
     */
    @PostMapping("/checkProjectCodeUnique")
    public AjaxResult checkProjectCodeUnique(@RequestBody PackProject packProject)
    {
        return success(packProjectService.checkProjectCodeUnique(packProject));
    }

    /**
     * 导入项目数据
     */
    @PreAuthorize("@ss.hasPermi('pack:project:import')")
    @Log(title = "项目", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<PackProject> util = new ExcelUtil<PackProject>(PackProject.class);
        List<PackProject> projectList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = packProjectService.importProject(projectList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载项目导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<PackProject> util = new ExcelUtil<PackProject>(PackProject.class);
        util.importTemplateExcel(response, "项目数据");
    }

    /**
     * 获取公司下的项目列表
     */
    @GetMapping("/companyProjects/{companyId}")
    public AjaxResult getProjectsByCompanyId(@PathVariable("companyId") Long companyId)
    {
        List<PackProject> list = packProjectService.selectProjectsByCompanyId(companyId);
        return success(list);
    }

    /**
     * 获取用户权限范围内的项目
     */
    @GetMapping("/dataScope")
    public AjaxResult getProjectsByDataScope(PackProject packProject)
    {
        List<PackProject> list = packProjectService.selectProjectsByDataScope(packProject);
        return success(list);
    }
    
    /**
     * 获取项目的物料列表（器具信息）
     */
    @PreAuthorize("@ss.hasPermi('pack:project:query')")
    @GetMapping("/{projectId}/materials")
    public AjaxResult getProjectMaterials(@PathVariable("projectId") Long projectId)
    {
        List<PackProjectMaterial> list = packProjectMaterialService.selectPackProjectMaterialByProjectId(projectId);
        return success(list);
    }
} 